package com.polaris.live.ui.set

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.View
import com.blankj.utilcode.util.StringUtils
import com.lxj.xpopup.XPopup
import com.polaris.live.BuildConfig
import com.polaris.live.R
import com.polaris.live.common.AppModule
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.AppConst
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.convertArabicDigitsToNormal
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.util.ImmersionBarBuilder
import com.polaris.live.common.util.SystemUtils
import com.polaris.live.constant.UserConst.UserSetting
import com.polaris.live.databinding.ActivitySettingBinding
import com.polaris.live.dialog.DmaDialog
import com.polaris.live.dialog.OpenVipDialog
import com.polaris.live.manager.AppConfigManager
import com.polaris.live.popup.SetSystemLanguagePopup
import com.polaris.live.ui.login.BaseGoogleLoginActivity
import com.polaris.live.utils.CommonUtils
import com.polaris.live.utils.CommonUtils.toBoolean
import com.polaris.live.utils.DmaUtils
import com.polaris.live.utils.OtherPermissionUtils
import com.polaris.live.utils.RichCharmImgUtil
import com.polaris.live.utils.UserUtils
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import com.polaris.live.viewmodel.SetViewModel

/**
 * SettingActivity
 *
 * @author Created by 半仙 on 2023/9/4/004 15:03
 */
class SettingActivity : BaseGoogleLoginActivity<SetViewModel, ActivitySettingBinding>() {

    override fun ImmersionBarBuilder.buildImmersionBar() {
        setNavigationBarColor(R.color.color_f8f9fa)
    }

    @SuppressLint("LogNotTimber")
    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        mBinding.tvVersion.text = "V ${AppModule.getVersionName()}"

        val preVersion = AppConfigManager.getConfigPre()?.forceVersion
        if (preVersion != null && preVersion.buildVersion > AppModule.getAppVersion()) {
            mBinding.vVersionDot.visibility = View.VISIBLE
        } else {
            mBinding.vVersionDot.visibility = View.INVISIBLE
        }

        val dndLevel = AppConfigManager.getConfig(CommonConst.Configs.messageDndLevelRich)?.toIntOrNull() ?: 6
        val (richLevel, _, _) = RichCharmImgUtil.getRichImg(UserManager.getUser().account?.richs ?: 0)
        if (richLevel >= dndLevel) {
            mBinding.messageNoDisturbance.visibility = View.VISIBLE
        } else {
            mBinding.messageNoDisturbance.visibility = View.GONE
        }
        if (UserManager.getUser().setting?.liveSwitch == null) {
            mBinding.livePermissions.visibility = View.GONE
        }
        initObserve()
        initDate()
        initListener()
    }

    private fun initDate() {
        mBinding.switchLiveBtn.isChecked = UserManager.getUser().setting?.liveNotice != 0
        mBinding.switchMessageBtn.isChecked = UserManager.getUser().setting?.chatNotice != 0
        mBinding.switchIncomingCallBtn.isChecked = UserManager.getUser().setting?.callNotice != 0
        mBinding.switchEssageNo.isChecked = UserManager.getUser().setting?.messageDnd != 0
        mBinding.switchLuckyBagBtn.isChecked = UserManager.getUser().setting?.luckyBagNotice.toBoolean()
        mBinding.switchLiveModule.isChecked = UserManager.getUser().setting?.liveSwitch.toBoolean()
        mBinding.switchMinimizeBtn.isChecked = UserManager.getUser().setting?.minimizeExitRoom.toBoolean()
        mBinding.switchInviteBtn.isChecked = UserManager.getUser().setting?.roomInviteDnd.toBoolean()

        mViewModel.getCacheSize()

        UserManager.getUser().profile?.appLanguage?.let {
            mBinding.tvLanguage.text = CommonUtils.getLanguage(it)
        }

        if (DmaUtils.isDmaDialogShowed()) {
            mBinding.csPrivacyList.visibility = View.VISIBLE
        }
    }

    private fun initListener() {
        mBinding.csAccount.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.SET_ACCOUNT_BIND_ACTIVITY).navigation(this)
        }

        mBinding.csChangePassword.setOnSingleClickListener {
            val user = UserManager.getUser()
            if (user.phoneNumber.isNullOrEmpty() && user.loginEmail.isNullOrEmpty()) {
                //优先绑定邮箱
                if (user.loginEmail.isNullOrEmpty()) {
                    Router.instance.setPath(RoutePath.BIND_GMAIL_ACTIVITY).navigation(this)
                } else {
                    Router.instance.setPath(RoutePath.BIND_PHONE_ACTIVITY).navigation(this)
                }
            } else {
                verifyGoogle {
                    Router.builder(RoutePath.SET_PASSWORD_ACTIVITY)
                        .withBoolean("isLogin", false)
                        .withBoolean("isFirstSet", user.hasPassword == 0)
                        .run {
                            if (!user.loginEmail.isNullOrEmpty()) {
                                withString("gmail", user.loginEmail ?: "")
                            } else {
                                withString("phoneNumber", user.phoneNumber ?: "")
                                    .withString("areaCode", user.areaCode ?: "")
                            }
                        }
                        .withString("googleValidate", it ?: "")
                        .withBoolean("isSettingCome", true)
                        .navigation(this)
                }
            }
        }



        mBinding.csAppLanguage.setOnSingleClickListener {
            XPopup.Builder(this)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(SetSystemLanguagePopup(this, mViewModel))
                .show()
        }

        mBinding.weekCl.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.WEEK_CALL_Activity).navigation(this)
        }

        mBinding.csBlockList.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.SET_BLOCK_ACTIVITY).navigation(this)
        }

        mBinding.csFeedback.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.FEEDBACK_AND_SUGGESTION).navigation(this)
        }
        mBinding.csAbout.setOnSingleClickListener {
            Router.instance.setPath(RoutePath.SET_ABOUT_ACTIVITY).navigation(this)
        }
        mBinding.csClearCache.setOnSingleClickListener {
            mViewModel.clearCache()
        }
        mBinding.csVersion.setOnSingleClickListener {
            if (mBinding.vVersionDot.visibility == View.VISIBLE) {
                SystemUtils.launchAppDetail(BuildConfig.APPLICATION_ID)
            }
        }
        mBinding.csPrivacyList.setOnSingleClickListener {
            DmaDialog.showDmaDialog(this, forceShow = true, isCancel = true)
        }

        // 添加监听
        mBinding.switchLiveBtn.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mViewModel.settingModify(UserSetting.LIVE_NOTICE, AppConst.YES)
            } else {
                mViewModel.settingModify(UserSetting.LIVE_NOTICE, AppConst.NO)
            }
        }

        mBinding.switchMessageBtn.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mViewModel.settingModify(UserSetting.CHAT_NOTICE, AppConst.YES)
            } else {
                mViewModel.settingModify(UserSetting.CHAT_NOTICE, AppConst.NO)
            }
        }

        mBinding.switchIncomingCallBtn.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mViewModel.settingModify(UserSetting.CALL_NOTICE, AppConst.YES)
            } else {
                mViewModel.settingModify(UserSetting.CALL_NOTICE, AppConst.NO)
            }
        }
        mBinding.switchEssageNo.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mViewModel.settingModify(UserSetting.MESSAGE_DND, AppConst.YES)
            } else {
                mViewModel.settingModify(UserSetting.MESSAGE_DND, AppConst.NO)
            }
        }
        mBinding.switchLuckyBagBtn.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mViewModel.settingModify(UserSetting.LUCKY_BAG_NOTICE, AppConst.YES)
            } else {
                mViewModel.settingModify(UserSetting.LUCKY_BAG_NOTICE, AppConst.NO)
            }
        }
        mBinding.switchLiveModule.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                mViewModel.settingModify(UserSetting.LIVE_MODULE_SWITFCH, AppConst.YES)
            } else {
                mViewModel.settingModify(UserSetting.LIVE_MODULE_SWITFCH, AppConst.NO)
            }

        }
        mBinding.switchMinimizeBtn.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                OtherPermissionUtils.checkAndRequestOverlayPermission(this) {
                    mViewModel.settingModify(UserSetting.MINIMIZE, AppConst.YES)
                }
            } else {
                mViewModel.settingModify(UserSetting.MINIMIZE, AppConst.NO)
            }
        }
        mBinding.loginOut.setOnSingleClickListener {
            mViewModel.logout()
        }
        mBinding.switchInviteBtn.setOnCheckedChangeListener { buttonView, isChecked ->
            if (buttonView.isPressed) {
                mBinding.switchInviteBtn.isChecked = !isChecked
                if (isChecked) {
                    mViewModel.settingModify(UserSetting.INVITE_DO_NOT_DISTURB, AppConst.YES)
                } else {
                    mViewModel.settingModify(UserSetting.INVITE_DO_NOT_DISTURB, AppConst.NO)
                }
            }
        }
    }

    private fun initObserve() {
        mViewModel.logoutLiveData.observe(this) {
            //退出登录不用管接口是不是调用成功
            UserUtils.logout()
        }

        mViewModel.cacheSizeLiveData.observe(this) {
            mBinding.tvCacheSize.text = it?.convertArabicDigitsToNormal()
        }
        mViewModel.settingLiveData.observe(this) {
            when (it.first) {
                UserSetting.INVITE_DO_NOT_DISTURB -> {
                    mBinding.switchInviteBtn.isChecked = it.second.toBoolean()
                }
            }
        }
        mViewModel.settingErrorLiveData.observe(this) {
            when (it.errCode) {
                CommonConst.ErrorCode.VIP_LEVEL_INSUFFICIENT -> {
                    val vipLevel = it.ext?.get("vipLevel").toString().toFloatOrNull()?.toInt()
                    vipLevel?.let { level ->
                        OpenVipDialog.show(
                            this,
                            StringUtils.getString(
                                com.polaris.live.translation.R.string.decline_an_invitation_is_vip_user,
                                "VIP$level"
                            ),
                            level
                        )
                    }
                }
            }
        }
    }
}